const dayjs = require('dayjs');
// 添加缺失的Helper引用，保持命名规范一致性
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper } = pathImport;;
const { logEvent } = require('../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../helpers/network_helper.js');

Page({
  data: {
    docId: null,
    document: null,
    comments: [],
    attachments: [],
    isLiked: false,
    commentInput: '',
    showEditMenu: false,
    showMoreMenu: false,
    showCommentInput: false,
    canEdit: false,
    canDelete: false,
    isLoading: true,
    isShowCommentInput: false,
    commentText: '',
    menuVisible: false,
    currentUserId: '' // 当前用户ID
  },

  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'knowledge_detail' });
    if (options.id) {
      this.setData({
        docId: options.id
      });
      this.loadDocumentDetail();
      this.loadComments();
      this.loadAttachments();
      this.checkEditPermission();
      this.getCurrentUser();
    } else {
      pageHelper.showModal('参数错误', '无法找到该文档');
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onPullDownRefresh() {
    this.loadDocumentDetail();
    this.loadComments();
    this.loadAttachments();
    wx.stopPullDownRefresh();
  },

  // 加载文档详情
  loadDocumentDetail() {
    const docId = this.data.docId;
    
    // 从本地存储加载文档列表
    const documents = wx.getStorageSync('local_knowledge_docs') || [];
    
    // 查找指定ID的文档
    const document = documents.find(doc => doc.id == docId);
    
    if (!document) {
        pageHelper.showModal('文档不存在或已被删除');
        setTimeout(() => {
            wx.navigateBack();
        }, 1500);
        return;
    }
    
    // 更新文档浏览量
    document.views = (document.views || 0) + 1;
    wx.setStorageSync('local_knowledge_docs', documents);
    
    // 将文档内容解析为可显示的格式
    const parsedContent = this._parseContent(document.content);
    
    this.setData({
        document: {
            ...document,
            parsedContent,
            commentCnt: 0, // 暂无评论功能
            isLiked: false // 暂无点赞功能
        },
        isLoading: false
    });
  },

  // 解析文档内容
  _parseContent(content) {
    if (!content) return [];
    
    // 简单解析，将文本按换行符分割
    const lines = content.split('\n');
    const parsedContent = [];
    
    lines.forEach(line => {
        // 如果是图片URL，则解析为图片
        if (line.match(/^(http|https):\/\/.*\.(jpg|jpeg|png|gif)$/i)) {
            parsedContent.push({
                type: 'image',
                url: line
            });
        } else if (line.trim()) {
            // 否则解析为文本
            parsedContent.push({
                type: 'text',
                text: line
            });
        }
    });
    
    return parsedContent;
  },

  // 加载评论列表
  loadComments() {
    // 模拟加载评论数据
    const mockComments = [
      {
        id: 1,
        author: {
          id: 2,
          name: '李四',
          avatar: '/images/avatar.png'
        },
        content: '文档写得很详细，对团队开发很有帮助！',
        time: '2024-03-20 15:00',
        replies: [
          {
            id: 11,
            author: '张三',
            content: '感谢支持！'
          }
        ]
      }
    ];

    this.setData({
      comments: mockComments
    });
  },

  // 加载附件列表
  loadAttachments() {
    // 模拟加载附件数据
    const mockAttachments = [
      {
        id: 1,
        name: '前端开发规范.pdf',
        size: '2.5MB',
        type: 'pdf',
        url: 'https://example.com/file.pdf'
      }
    ];

    this.setData({
      attachments: mockAttachments
    });
  },

  // 检查编辑权限
  checkEditPermission() {
    // 模拟检查权限
    this.setData({
      canEdit: true
    });
  },

  // 切换点赞状态
  toggleLike() {
    const newLikeStatus = !this.data.isLiked;
    const document = this.data.document;
    document.likes += newLikeStatus ? 1 : -1;
    
    this.setData({
      isLiked: newLikeStatus,
      document: document
    });

    // TODO: 调用后端API更新点赞状态
    console.log('更新点赞状态:', newLikeStatus);
  },

  // 显示评论输入框
  showCommentInput() {
    this.setData({
      showCommentInput: true
    });
  },

  // 隐藏评论输入框
  hideCommentInput() {
    this.setData({
      showCommentInput: false,
      commentInput: ''
    });
  },

  // 处理评论输入
  onCommentInput(e) {
    this.setData({
      commentInput: e.detail.value
    });
  },

  // 发送评论
  sendComment() {
    if (!this.data.commentInput.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    // 模拟发送评论
    const newComment = {
      id: dayjs().valueOf(),
      author: {
        id: 1,
        name: '当前用户',
        avatar: '/images/avatar.png'
      },
      content: this.data.commentInput,
      time: '刚刚',
      replies: []
    };

    this.setData({
      comments: [newComment, ...this.data.comments],
      commentInput: '',
      showCommentInput: false
    });

    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });

    // TODO: 调用后端API保存评论
    console.log('发送评论:', newComment);
  },

  // 下载附件
  downloadAttachment(e) {
    const { id } = e.currentTarget.dataset;
    const attachment = this.data.attachments.find(item => item.id === id);
    
    if (attachment) {
      wx.showLoading({
        title: '下载中...'
      });

      // TODO: 实现文件下载逻辑
      setTimeout(() => {
        wx.hideLoading();
        wx.showToast({
          title: '下载成功',
          icon: 'success'
        });
      }, 1500);
    }
  },

  // 显示/隐藏编辑菜单
  toggleEditMenu() {
    if (!this.data.canEdit) {
      wx.showToast({
        title: '您没有编辑权限',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showEditMenu: !this.data.showEditMenu
    });
  },

  // 编辑文档
  editDocument() {
    this.setData({
      showEditMenu: false
    });
    wx.navigateTo({
      url: `/pages/knowledge/edit/knowledge_edit?id=${this.data.docId}`
    });
  },

  // 分享文档
  onShareAppMessage() {
    return {
      title: this.data.document.title,
      path: `/pages/knowledge/detail/knowledge_detail?id=${this.data.docId}`
    };
  },

  // 显示更多操作菜单
  onMoreTap() {
    this.setData({
      showMoreMenu: !this.data.showMoreMenu
    });
  },

  // 跳转到评论输入页面
  onCommentTap() {
    wx.navigateTo({
      url: `/pages/knowledge/comment/knowledge_comment?id=${this.data.docId}`
    });
  },

  // 编辑文档
  onEditTap() {
    this.setData({
      showMoreMenu: false
    });
    wx.navigateTo({
      url: `/pages/knowledge/edit/knowledge_edit?id=${this.data.docId}`
    });
  },

  // 删除文档
  onDeleteTap() {
    this.setData({
      showEditMenu: false
    });
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这篇文档吗？此操作不可恢复。',
      confirmText: '删除',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用后端API删除文档
          wx.showLoading({
            title: '删除中...'
          });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  wx.navigateBack();
                }, 2000);
              }
            });
          }, 1500);
        }
      }
    });
  },

  // 预览图片
  previewImage(e) {
    const { url } = e.currentTarget.dataset;
    const urls = this.data.document.parsedContent
      .filter(item => item.type === 'image')
      .map(item => item.url);
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: async function() {
    try {
      const userInfo = await cloudHelper.callCloudData('user/my_detail');
      if (userInfo && userInfo.USER_MINI_OPENID) {
        this.setData({
          currentUserId: userInfo.USER_MINI_OPENID
        });
      }
    } catch (err) {
      console.error('获取用户信息失败', err);
    }
  },
  
  /**
   * 标记文档为已完成
   */
  markAsComplete() {
    try {
        const docId = this.data.document.id;
        
        // 从本地存储加载文档列表
        const documents = wx.getStorageSync('local_knowledge_docs') || [];
        
        // 查找并更新指定ID的文档
        const docIndex = documents.findIndex(doc => doc.id == docId);
        
        if (docIndex >= 0) {
            documents[docIndex].status = 'completed';
            wx.setStorageSync('local_knowledge_docs', documents);
            
            // 更新当前页面显示
            this.setData({
                'document.status': 'completed'
            });
            
            pageHelper.showSuccToast('已标记为完成');
            
            // 模拟通知提示
            setTimeout(() => {
                wx.showModal({
                    title: '通知',
                    content: `已通知文档创建者 "${this.data.document.author.name}" 文档已完成。\n(注：由于技术原因，实际无法发送通知)`,
                    showCancel: false
                });
            }, 1500);
        }
    } catch (err) {
        console.error('标记完成失败', err);
        pageHelper.showModal('操作失败，请重试');
    }
  },
}); 